package com.easymin.weixin.manager.impl;

import com.easymin.weixin.common.DataForm;
import com.easymin.weixin.common.DataGrid;
import com.easymin.weixin.entity.Admin;
import com.easymin.weixin.manager.AdminManager;
import com.easymin.weixin.service.AdminService;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by shine on 15/8/19.
 */
@Service
public class DefaultAdminManager implements AdminManager {

  @Autowired
  private AdminService adminService;

  @Override
  public DataGrid<Admin> findAll(int page, int rows) {

    int offset = (page - 1) * rows;

    RowBounds rowBounds = new RowBounds(offset, rows);

    List<Admin> admins = adminService.findAll(rowBounds);
    long total = adminService.count();

    DataGrid<Admin> dataGrid = new DataGrid<>();
    dataGrid.setRows(admins);
    dataGrid.setTotal(total);

    return dataGrid;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public DataForm<Admin> insert(Admin admin) {

    DataForm<Admin> dataForm = new DataForm<>();

    boolean exists = adminService.exists(admin.getUsername());

    if (!exists) {

      // 密码要加密
      Sha256Hash sha256Hash = new Sha256Hash(admin.getPassword());
      admin.setPassword(sha256Hash.toBase64());

      adminService.insert(admin);
      dataForm.setStatus(0);
      dataForm.setMessage("成功");
      dataForm.setData(admin);
    } else {
      dataForm.setStatus(-1);
      dataForm.setMessage("用户名已经存在");
    }

    return dataForm;
  }

  @Override
  public Admin fetch(Long id) {

    return adminService.fetch(id);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public DataForm<Admin> updateByPrimaryKey(Admin admin) {

    DataForm<Admin> dataForm = new DataForm<>();

    Admin local = adminService.fetch(admin.getId());

    if (null != local) {

      local.setName(admin.getName());
      if (StringUtils.isNotBlank(admin.getPassword())) {
        // 密码要加密
        Sha256Hash sha256Hash = new Sha256Hash(admin.getPassword());
        local.setPassword(sha256Hash.toBase64());
      }

      adminService.update(local);

      dataForm.setData(local);
      dataForm.setStatus(0);
      dataForm.setMessage("成功");
    } else {
      dataForm.setStatus(-1);
      dataForm.setMessage("管理员不存在");
    }


    return dataForm;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public DataForm<Admin> deleteByPrimaryKey(Long id) {

    DataForm<Admin> dataForm = new DataForm<>();

    adminService.delete(id);
    dataForm.setStatus(0);
    dataForm.setMessage("成功");

    return dataForm;
  }

  @Override
  public Admin findByUsername(String username) {
    return adminService.findByUsername(username);
  }
}
